/**
 * Copyright (c) 2011 Tomi Paananen.
 *
 * Part of Quick Gestures test tool.
 */

#include "statistics.h"

// Qt includes
#include <QDateTime>
#include <QDebug>
#include <QFile>
#include <QTextStream>


/*!
  \class Statistics
  \brief TODO
*/

/*!
  Constructor.
*/
Statistics::Statistics()
    : m_maxLength(0)
{
}


/*!
  Destructor.
*/
Statistics::~Statistics()
{
    clear();
}


/*!
*/
bool Statistics::addValue(const QString &testSetId, int sampleGestureIndex,
                          int recognizedIndex, int difference)
{
    qDebug() << "Statistics::addValue():" << testSetId << sampleGestureIndex
             << recognizedIndex << difference;

    if (m_statisticsMap.find(testSetId) != m_statisticsMap.end()) {
        qDebug() << "The test set ID" << testSetId << "already exists.";

        // Get the list with the given ID.
        QList<CellData*> cellDataList = m_statisticsMap.value(testSetId);

        if (cellDataList.count() <= sampleGestureIndex) {
            while (cellDataList.count() < sampleGestureIndex) {
                // Insert empty data until the index is matched.
                cellDataList.append(new CellData());
            }

            cellDataList.append(new CellData(difference, recognizedIndex));
        }
        else {
            cellDataList[sampleGestureIndex]->m_difference = difference;
            cellDataList[sampleGestureIndex]->m_index = recognizedIndex;
        }

        m_statisticsMap.insert(testSetId, cellDataList);
    }
    else {
        qDebug() << "No" << testSetId << "in the map.";

        // Create a new list of cell data.
        QList<CellData*> cellDataList;

        for (int i = 0; i < sampleGestureIndex; ++i) {
            // Insert empty data until the index is matched.
            cellDataList.append(new CellData());
        }

        cellDataList.append(new CellData(difference, recognizedIndex));
        m_statisticsMap.insert(testSetId, cellDataList);
    }

    if (sampleGestureIndex + 1 > m_maxLength) {
        m_maxLength = sampleGestureIndex + 1;
    }

    return true;
}


/*!
  Clears the statistics.
*/
void Statistics::clear()
{
    QList<QString> keys = m_statisticsMap.keys();

    foreach (QString key, keys) {
        qDeleteAll(m_statisticsMap.value(key));
    }

    m_statisticsMap.clear();
    m_metaData.clear();
    m_maxLength = 0;
}


/*!
*/
void Statistics::setMetaData(QString metaData)
{
    m_metaData = metaData;
}


/*!
*/
bool Statistics::exportAsHTML(const QString &filePath)
{
    QFile file(filePath);

    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        return false;
    }

    QTextStream textStream(&file);

    // Write meta data.
    textStream << "<p>\nDate: " << QDateTime::currentDateTime().toString() << "<br />\n"
               << m_metaData << "</p>\n";

    // Write the top header row.
    textStream << "<table>\n<tr><th>Index</th>";

    for (int i = 0; i < m_maxLength; ++i) {
        textStream << "<th>" << i << "</th>";
    }

    textStream << "<th>Success rate</th></tr>\n";

    int successByIndex[m_maxLength];

    for (int i = 0; i < m_maxLength; ++i) {
        successByIndex[i] = 0;
    }

    int testSetSuccess(0);
    int overallSuccess(0);

    // Write the statistics rows.
    foreach (QString key, m_statisticsMap.keys()) {
        textStream << "<tr><th>" << key << "</th>";

        QList<CellData*> cellDataList = m_statisticsMap.value(key);

        for (int i = 0; i < cellDataList.count(); ++i) {
            textStream << "<td style=\"background-color: ";

            if (cellDataList[i]) {
                if (cellDataList[i]->m_index == i) {
                    // Correct index!
                    textStream << "#ccffcc\">";
                    testSetSuccess += 1;
                    successByIndex[i] += 1;
                }
                else {
                    // Failed recognition!
                    textStream << "#ffcccc\">";
                }

                textStream << cellDataList[i]->m_index << "; "
                           << cellDataList[i]->m_difference;
            }
            else {
                textStream << "\">";
            }

            textStream << "</td>";
        }

        textStream << "<td>"
                   << QString::number((qreal)testSetSuccess * 100
                                      / (qreal)m_maxLength, 'g', 3)
                   << " % (" << testSetSuccess << "/" << m_maxLength
                   << ")</td></tr>\n";
        overallSuccess += testSetSuccess;
        testSetSuccess = 0;
    } // foreach key

    // Write the success rate row.
    textStream << "<tr><th>Success rate</th>";

    for (int i = 0; i < m_maxLength; ++i) {
        textStream << "<td>"
                   << QString::number((qreal)successByIndex[i] * 100
                                      / (qreal)m_statisticsMap.count(), 'g', 3)
                   << " % (" << successByIndex[i] << "/" << m_statisticsMap.count()
                   << ")</td>";
    }

    textStream << "<td>"
               << QString::number((qreal)overallSuccess * 100
                                  / (qreal)(m_maxLength * m_statisticsMap.count()),
                                  'g', 3)
               << " % (" << overallSuccess << "/"
               << m_maxLength * m_statisticsMap.count()
               << ")</td></tr>\n";

    // Close the table.
    textStream << "</table>";

    file.close();
    return true;
}

